package com.jarvis.hospital.patient;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jarvis.hospital.R;
import com.jarvis.hospital.common.BaseActivity;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.login.model.LoginModel;
import com.jarvis.hospital.login.model.UserModel;
import com.jarvis.hospital.patient.adapter.MessageDetailAdapter;
import com.jarvis.hospital.patient.model.MessageListModel;
import com.jarvis.hospital.patient.model.MessageModel;
import com.jarvis.hospital.prescription.NewPrescriptionActivity;
import com.jarvis.hospital.prescription.adapter.DefaultPrescriptionAdapter;
import com.jarvis.hospital.prescription.adapter.PrescriptionTimeAdapter;
import com.jarvis.hospital.prescription.model.PrescriptionItemModel;
import com.jarvis.hospital.prescription.model.PrescriptionModel;
import com.jarvis.hospital.prescription.model.PrescriptionTimeDetailModel;
import com.jarvis.hospital.prescription.model.PrescriptionTimeModel;
import com.jarvis.hospital.servers.ApiService;
import com.jarvis.hospital.util.DividerItemDecoration;
import com.jarvis.hospital.util.SharePreferenceKey;
import com.jarvis.hospital.util.SharePreferenceUtils;
import com.jarvis.hospital.util.net.RequestApi;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MessageDetailsActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.recy_message)
    RecyclerView recy_message;
    @BindView(R.id.ptr_message)
    PtrClassicFrameLayout ptr_message;
    private MessageDetailAdapter messageDetailAdapter;
    private int pageSize = 10;
    private int currentPage = 1;
    private int maxPage = 1;
    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.ed_value)
    EditText ed_value;
    @BindView(R.id.tv_send)
    TextView tv_send;
    private ApiService service;
    private String smsReceiverId;

    @Override
    public int getLayoutId() {
        return R.layout.activity_message_details;
    }

    @Override
    public void initData() {

        ptr_message.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        ptr_message.autoRefresh();
                    }
                }, 100);
    }

    @Override
    public void initView() {
        Bundle bundle = this.getIntent().getExtras();
        String name = bundle.getString("name");
        smsReceiverId = bundle.getString("smsReceiverId");
        service = RequestApi.create(ApiService.class);
        //setStatus(false);
        tv_title.setText(name);
        rel_left.setOnClickListener(this);
        tv_send.setOnClickListener(this);
        setAdapter();
        setRefresh();
    }

    /**
     * 设置下拉刷新
     */
    public void setRefresh() {
        ptr_message.setMode(PtrFrameLayout.Mode.REFRESH);
        ptr_message.disableWhenHorizontalMove(true);
        ptr_message.setLastUpdateTimeRelateObject(this);
        ptr_message.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return PtrDefaultHandler2.checkContentCanBePulledUp(frame, recy_message, footer);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler2.checkContentCanBePulledDown(frame, recy_message, header);
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                if (currentPage < maxPage) {
                    currentPage++;
                    loadData();
                } else {
                    ptr_message.refreshComplete();
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (currentPage == 1) {
                    messageDetailAdapter.setNewData(new ArrayList<MessageModel>());
                    loadData();
                } else {
                    if (currentPage <= maxPage) {
                        loadData();
                    } else {
                        ptr_message.refreshComplete();
                    }
                }
            }
        });
    }

    /**
     * 设置adapter
     */
    public void setAdapter() {
        messageDetailAdapter = new MessageDetailAdapter(R.layout.item_message_detail, new ArrayList<MessageModel>());
        recy_message.setLayoutManager(new LinearLayoutManager(this));
        //recy_time.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        messageDetailAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recy_message.setAdapter(messageDetailAdapter);
    }

    private void sendMessage() {
        String content = ed_value.getText().toString();
        if (TextUtils.isEmpty(content)) {
            showTextToast("不能发送空消息");
            return;
        }
        showDialog("加载中");
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userId = userModel.getUserId();
        service.sendMessage(content, userId, smsReceiverId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData messageListModelResponseData) {
                        if (messageListModelResponseData != null) {
                            int resultCode = messageListModelResponseData.getResultCode();
//                            if (resultCode == 200) {
//                                ptr_message.postDelayed(
//                                        new Runnable() {
//                                            @Override
//                                            public void run() {
//                                                ptr_message.autoRefresh();
//                                            }
//                                        }, 100);
//                            } else {
//                                showTextToast(messageListModelResponseData.getMessage());
//                            }
                            ed_value.setText("");
                            currentPage = 1;
                            ptr_message.postDelayed(
                                    new Runnable() {
                                        @Override
                                        public void run() {
                                            ptr_message.autoRefresh();
                                        }
                                    }, 100);
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }

    private void loadData() {
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userId = userModel.getUserId();
        service.getMessage(currentPage, pageSize, userId, smsReceiverId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<MessageListModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<MessageListModel> messageListModelResponseData) {
                        if (messageListModelResponseData != null) {
                            int resultCode = messageListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                int total_count = messageListModelResponseData.getTotalcount();
                                maxPage = total_count % pageSize == 0 ? total_count / pageSize : total_count / pageSize + 1;
                                if (currentPage == 1) {
                                    messageDetailAdapter.addData(messageListModelResponseData.getData().getMsgList());
                                    recy_message.scrollToPosition(messageDetailAdapter.getItemCount() - 1);
                                } else {
                                    List<MessageModel> data = messageDetailAdapter.getData();
                                    messageDetailAdapter.setNewData(new ArrayList<MessageModel>());
                                    messageDetailAdapter.addData(messageListModelResponseData.getData().getMsgList());
                                    messageDetailAdapter.addData(data);
                                    ((LinearLayoutManager)recy_message.getLayoutManager()).scrollToPositionWithOffset(messageListModelResponseData.getData().getMsgList().size(),0);
//                                    recy_message.scrollToPosition(messageListModelResponseData.getData().getMsgList().size());
                                }
                                if (messageListModelResponseData.getData().getMsgList().size() != 0) {
                                    currentPage++;
                                }
                            } else {
                                showTextToast(messageListModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ptr_message.refreshComplete();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        ptr_message.refreshComplete();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_left:
                finish();
                break;
            case R.id.tv_send:
                sendMessage();
                break;
        }
    }
}
